﻿var DATA_CONTEXT_KEY = "DataContext";
var DATA_TEMPLATE_KEY = "Template";

window.dummy = function () { }

window.fix_input_boxes = function () {
    $.preferCulture("zh-CN");

    if ($(".DateTimeClass").size() > 0) {
        $(".DateTimeClass").datepicker();
    }

    // TODO: 在使用jquery.dialog方法打开的对话框里，下面的语句不起作用
    if ($(".HtmlClass").size() > 0) {
        $(".HtmlClass").tinymce({
            mode: "textareas",
            theme: "simple"
        });
    }
};

window.applyServerTemplate = function (instance) {
    if (instance instanceof Array) {
        instance = {
            dataContext: instance
        };
    }
    var elem = $('#item_template').tmpl(instance);
    elem.prependTo('#viewpot');
};

function assemble_data(arr, tmplobj) {
    var result = {};
    var children = new Array();
    var idics = {};
    // TODO: 这个变量只能实现支持包含两个属性的对象，不能通用化
    var partialObject = false;

    for ( var i = 0; i < arr.length; ++i ) {
        var a = arr[i];
        var propName = a.name;
        var propNames = propName.split(".");
        propName = propNames[0];

        if (tmplobj.hasOwnProperty(propName)) {
            var idx = 0;
            var isArrayProperty = tmplobj[propName] instanceof Array;

            if ( isArrayProperty ) {
                if (idics.hasOwnProperty(propName))
                    idx = idics[propName];
                else
                    idx = 0;

                if (!result.hasOwnProperty(propName))
                    result[propName] = new Array();

                var collection = result[propName];
                var tmplObj = tmplobj[propName][0];
                var obj;

                // TODO: 这个变量只能实现支持包含两个属性的对象，不能通用化
                if (partialObject)
                    obj = collection[idx];
                else
                    obj = $.extend({}, tmplObj);

                for (var prop in tmplObj) {
                    // TODO: 这个变量只能实现支持包含两个属性的对象，不能通用化
                    if (propNames.length > 1 && prop == propNames[1]) {
                        obj[prop] = a.value;
                        partialObject = !partialObject;
                    }
                    else if (propNames.length == 1) {
                        // TODO: 这个变量只能实现支持包含两个属性的对象，不能通用化
                        partialObject = false;
                        obj[prop] = a.value;
                    }
                }

                collection[idx] = obj;
                // TODO: 这个变量只能实现支持包含两个属性的对象，不能通用化
                if (!partialObject) idx++;
                idics[propName] = idx;
            }
            else if ( propNames.length > 1 ) {  
                // 是一个引用类型的属性
                partialObject = false;
                var propObj = {};
                propObj[propNames[1]] = a.value;
                result[propName] = propObj;
            }
            else {
                // TODO: 这个变量只能实现支持包含两个属性的对象，不能通用化
                partialObject = false;
                result[propName] = a.value;
            }
        }
        else {
            // TODO: 这个变量只能实现支持包含两个属性的对象，不能通用化
            partialObject = false;
            result[propName] = a.value;
        }
    }

    return result;
};

window.register_submit_handler = function(tmplobj, successCallback) {
    $('#submit_btn').click(function () {
        var form = $('#submit_btn').parents('form');
        var newitem = assemble_data($(form).serializeArray(), tmplobj);

        $.ajax({
            type: 'POST',
            url: $(form).attr('action'),
            dataType: 'json',
            data: JSON.stringify(newitem),
            contentType: 'application/json; charset=utf-8',
            success: successCallback
        });
    });
};

function S4() {

   return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
}

window.guid = function() {
   return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
};

window.applyTemplate = function(templateText, data, okfunc) {
	var editor = $('#child_editor');
	$(editor).empty();
	var elem = $.tmpl(templateText, data);
	elem.appendTo(editor);
    fix_input_boxes();
    $('#action_dialog').dialog('close');        

	$(editor).dialog({
	    modal: true,
        width: 600,
	    buttons: {
	        "确定": okfunc,
            "取消": function() { $(this).dialog("close"); }
	    }
	});

	return editor;
};

window.openModelWindow = function(address, callback) {
	$.ajax({
	    url: address,
	    success: callback
	});
    $('#child_editor').load(address, callback);
};
    
window.selectingChildItem = function(address, templateText, template) {
	$.ajax({
        url: address, 
        success: function (data) {
	        eval('var wrapper = { dataContext: ' + data + '};');

	        var dialog = applyTemplate(templateText, wrapper, function () {
	            var elems = $(this).find('#select_item_chk');
	            $.each(elems, function (i, a) {
	                if ($(a).attr('checked')) {
	                    var item = wrapper.dataContext[i];
	                    $(template).tmpl(item).appendTo('#children');
	                }
	            });

	            $(this).dialog('close');
	        });
	    },
        error: function (xhr, status, e) {
            window.alert('failed');
        }
    });
};

window.creatingChild = function(url, templateText, template, tmplobj) {
	$('#child_editor').empty();

	var dialog = applyTemplate(templateText, tmplobj, function () {     
        var postData = assemble_data($(this).serializeArray(), tmplobj);

        $.ajax({
            url : url,
            type: 'POST',
            dataType: 'json',
            data: JSON.stringify(postData),
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                $(template).tmpl(data).appendTo('#children');
            }
        });

        $(this).dialog('close');
	});
};